import { Auths, Role } from '@/utils/types.d';
import {
  ProForm,
  ProFormDigit,
  ProFormGroup,
  ProFormSelect,
  ProFormSwitch,
  ProCard,
  FooterToolbar,
} from '@ant-design/pro-components';
import { useEffect, useState } from 'react';
import { useModel } from 'umi';
import { editAboConfig, getAboConfig } from './service';
import { queryCompanies } from '../SystemUser/service';
import { message } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';

const DEFAULT: ABOConfigTableItem = {
  enable: false,
  sensorOccupy: { enable: false, timeout: 0 },
  sensorFree: { enable: false, timeout: 0 },
  unknownLicense: { enable: false, timeout: 0 },
  licenseSimilar: { enable: false, timeout: 0 },
  licenseChanged: { enable: false, timeout: 0 },
  licenseConflict: { enable: false, timeout: 0 },
};

const ABODesc = (props: { title: string; desc: string }) => (
  <p>
    <b>{props.title}：</b>
    <span>{props.desc}</span>
  </p>
);
const AboConfigPage = () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const isAdmin = currUser?.role === Role.ADMIN;
  const [ownerId, setOwnerId] = useState<string>(isAdmin ? '' : currUser?.ownerId || '');
  const [form] = ProForm.useForm();
  const auths = currUser?.auth ? new Set(currUser.auth.systemConfig || []) : new Set();
  const ifConfig = auths.has(Auths.ABO_CONFIG);
  const [chillDowning, setChillDowning] = useState<number>(0);
  const [currConfig, setCurrConfig] = useState<ABOConfigTableItem>(DEFAULT);
  if (chillDowning > -1) {
    setTimeout(() => {
      setChillDowning(chillDowning - 1);
    }, 1000);
  }
  useEffect(() => {
    if (!ownerId) return;
    getAboConfig(ownerId).then((res) => {
      if (!res || !res.data) return;

      setCurrConfig(res.data);
      form.setFieldsValue(res.data);
    });
  }, [ownerId]);
  return (
    <PageHeaderWrapper
      header={{
        breadcrumb: {
          routes: [
            {
              path: '/',
              breadcrumbName: '首页',
            },
            {
              path: '/setting-config',
              breadcrumbName: '系统配置',
            },
            {
              path: '/abo',
              breadcrumbName: '异常订单配置',
            },
          ],
        },
        subTitle: '异常订单配置',
      }}
      extra={
        isAdmin && (
          <ProFormSelect
            name="ownerId"
            label="配置公司"
            debounceTime={300}
            showSearch
            fieldProps={{
              value: ownerId,
              onChange: (val) => {
                if (ownerId != '') {
                  form?.setFieldsValue(DEFAULT);
                }
                setOwnerId(val);
              },
              style: {
                width: 280,
                margin: 0,
              },
            }}
            placeholder="请选择要进行配置公司"
            request={(val) => queryCompanies(val.keyWords, false)}
          />
        )
      }
    >
      <ProCard direction="row">
        <ProCard colSpan="50%" title="异常订单配置" headerBordered>
          <ProForm<ABOConfigTableItem>
            form={form}
            layout="horizontal"
            style={{
              padding: '0 24px',
            }}
            submitter={{
              searchConfig: {
                submitText: ifConfig ? '保存配置' : '无权限操作',
              },
              submitButtonProps: {
                disabled: !ifConfig || chillDowning > 0,
              },
              render: (_, dom) => <FooterToolbar>{dom}</FooterToolbar>,
            }}
            initialValues={currConfig}
            onFinish={async (values) => {
              if (!ownerId) {
                message.warn({ content: '请选择配置公司', key: 'checkOwnerRes' });
                return;
              }
              setCurrConfig({
                ...values,
              });
              setChillDowning(10);
              const res = await editAboConfig({
                ownerId,
                ...values,
              });
              if (!res.success) {
                message.error({ content: res.message, key: 'editAboConfigRes' });
                return false;
              }
              message.success({ content: '保存成功', key: 'editAboConfigRes' });
              return true;
            }}
          >
            <ProFormSwitch
              label="全局开关"
              name="enable"
              checkedChildren="开启"
              unCheckedChildren="关闭"
            />
            <ProFormGroup title="地磁有车，巡检无车异常">
              <ProFormSwitch label="是否生成异常订单" name={['sensorOccupy', 'enable']} />
              <ProFormDigit
                label="异常订单过期时间"
                name={['sensorOccupy', 'timeout']}
                fieldProps={{
                  precision: 0,
                  min: 0,
                }}
                addonAfter="分钟"
              />
            </ProFormGroup>
            <ProFormGroup title="地磁无车，巡检有车异常">
              <ProFormSwitch label="是否生成异常订单" name={['sensorFree', 'enable']} />
              <ProFormDigit
                label="异常订单过期时间"
                name={['sensorFree', 'timeout']}
                fieldProps={{ precision: 0, min: 0 }}
                addonAfter="分钟"
              />
            </ProFormGroup>
            <ProFormGroup title="地磁未变，车牌变化异常">
              <ProFormSwitch label="是否生成异常订单" name={['licenseChanged', 'enable']} />
              <ProFormDigit
                label="异常订单过期时间"
                name={['licenseChanged', 'timeout']}
                fieldProps={{ precision: 0, min: 0 }}
                addonAfter="分钟"
              />
            </ProFormGroup>
            <ProFormGroup title="未知车牌异常">
              <ProFormSwitch label="是否生成异常订单" name={['unknownLicense', 'enable']} />
              <ProFormDigit
                label="异常订单过期时间"
                name={['unknownLicense', 'timeout']}
                fieldProps={{ precision: 0, min: 0 }}
                addonAfter="分钟"
              />
            </ProFormGroup>

            <ProFormGroup title="车牌变更异常">
              <ProFormSwitch label="是否生成异常订单" name={['licenseSimilar', 'enable']} />
              <ProFormDigit
                label="异常订单过期时间"
                name={['licenseSimilar', 'timeout']}
                fieldProps={{ precision: 0, min: 0 }}
                addonAfter="分钟"
              />
            </ProFormGroup>

            <ProFormGroup title="车牌冲突异常">
              <ProFormSwitch label="是否生成异常订单" name={['licenseConflict', 'enable']} />
              <ProFormDigit
                label="异常订单过期时间"
                name={['licenseConflict', 'timeout']}
                fieldProps={{ precision: 0, min: 0 }}
                addonAfter="分钟"
              />
            </ProFormGroup>
          </ProForm>
        </ProCard>

        <ProCard colSpan="50%" title="配置说明" headerBordered style={{ fontSize: '16px' }}>
          <p>
            <pre style={{ display: 'inline', color: 'red' }}>* </pre>
            根据此处的配置判断是否在巡检过程中生成异常订单。若<b>未配置或配置未启用</b>
            ，默认丢弃<b>巡检数据</b>
          </p>
          <ABODesc
            title="全局开关"
            desc="控制异常订单配置的全局有效性。状态关闭时，默认不进行任何异常订单生成；状态开启后，逐项判断是否生成"
          />
          <ABODesc
            title="地磁有车，巡检无车异常"
            desc="巡检上报数据为空车，地磁（泊位）当前状态为占用；"
          />
          <ABODesc
            title="地磁无车，巡检有车异常"
            desc="巡检上报数据为有车，地磁（泊位）当前状态为空闲；"
          />
          <ABODesc
            title="地磁未变，车牌变化异常"
            desc="巡检车上报数据中，本次巡检车牌号码与当前泊位在停车牌号码不同；"
          />
          <ABODesc title="未知车牌异常" desc="巡检车上报数据中车牌号码为未知车牌或格式错误；" />
          <ABODesc
            title="车牌变更异常"
            desc="巡检车上报数据中，本次巡检车牌号码与当前泊位在停的车牌号码不同，且相似度>80%"
          />
          <ABODesc
            title="车牌冲突异常"
            desc="巡检车上报数据中，本次巡检车牌号码在其他泊位已有在停订单"
          />
          <ABODesc
            title="是否生成异常订单"
            desc="全局开关开启的状态前提下，是否生成当前异常类型的订单"
          />
          <ABODesc
            title="异常订单过期时间"
            desc="异常订单的处理有效时间；过期时间为0时，表示当前异常订单不会过期"
          />
        </ProCard>
      </ProCard>
    </PageHeaderWrapper>
  );
};

export default AboConfigPage;
